package com.drinks.yiniang.ui.fragment.user.invoice;


import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.invoice.InvoiceListAdapter;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.common.listener.OnCartHandleClickListener;
import com.drinks.yiniang.entity.user.invoice.InvoiceOrderListJson;
import com.drinks.yiniang.io.api.InvoiceApiIO;
import com.drinks.yiniang.ui.widget.layout.InvoiceOrderListBottomLayout;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.fragment.BaseFragment;
import com.hansen.library.utils.ArithmeticUtil;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 发票订单列表
 * Created by han on 2019/11/16
 * A simple {@link Fragment} subclass.
 */
public class InvoiceListFragment extends BaseFragment implements BaseQuickAdapter.OnItemChildClickListener, OnCartHandleClickListener {

    private BaseRecyclerView rcv_invoice_list;
    //底部bottom
    private InvoiceOrderListBottomLayout ll_invoice_list_bottom;

    private InvoiceListAdapter mInvoiceListAdapter;

    private OnInvoiceListSureListener onInvoiceListSureListener;

    public InvoiceListFragment() {
        // Required empty public constructor
    }

    public static InvoiceListFragment newInstance() {
        return new InvoiceListFragment();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            onInvoiceListSureListener = (OnInvoiceListSureListener) context;
        } catch (ClassCastException e) {
            LogUtils.e(context.toString() + "must implement OnInvoiceListSureListener");
        }
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_invoice_list;
    }

    @Override
    protected void initView(View mView) {
        rcv_invoice_list = mView.findViewById(R.id.rcv_invoice_list);

        ll_invoice_list_bottom = mView.findViewById(R.id.ll_invoice_list_bottom);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        initAdapter();
        getInvoiceOrderList();
    }

    private void initAdapter() {
        rcv_invoice_list.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_invoice_list.addItemDecoration(ItemSpacesDecoration.getItemDPDecoration(10));

        mInvoiceListAdapter = new InvoiceListAdapter(mContext, new ArrayList<InvoiceOrderListJson.InvoiceOrderList>());
        mInvoiceListAdapter.setCenterEmpty(getLayoutInflater(), rcv_invoice_list);
        mInvoiceListAdapter.bindToRecyclerView(rcv_invoice_list);
    }

    @Override
    protected void listener() {
        ll_invoice_list_bottom.setHandleClickListener(this);
        mInvoiceListAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void widgetClick(View v) {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        InvoiceOrderListJson.InvoiceOrderList data = mInvoiceListAdapter.getItem(position);

        if (data == null) {
            return;
        }

        switch (view.getId()) {
            case R.id.tv_invoice_list_check://选择
                setChecked(data, position);
                break;
            default:
                break;
        }
    }

    @Override
    public void onCheckAllClick(View v, boolean checkAll) {
        //全选或取消全选
        if (CommonUtils.isEmptyList(mInvoiceListAdapter.getData())) {
            return;
        }

        InvoiceOrderListJson.InvoiceOrderList data;
        String totalMoney = "0.0";
        int total = 0;

        for (int i = 0; i < mInvoiceListAdapter.getData().size(); i++) {
            data = mInvoiceListAdapter.getData().get(i);
            data.setChecked(checkAll);

            if(checkAll) {
                total++;
                totalMoney = ArithmeticUtil.addAmount(totalMoney, ArithmeticUtil.mulScaleAmount(data.getPay_amount(), data.getNum()));
            }
        }

        ll_invoice_list_bottom.setTotalText(String.valueOf(total), totalMoney);

        mInvoiceListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onToSettleAccountClick(View v) {
        doNext();
    }

    private void doNext() {
        String orderId = getSelectOrderId();

        if (StringUtils.isEmpty(orderId)) {
            ToastUtils.showShort(getString(R.string.text_select_need_invoice_order));
            return;
        }

        if (onInvoiceListSureListener != null) {
            onInvoiceListSureListener.onInvoiceSureClick(orderId);
        }
    }

    //设置选中
    private void setChecked(InvoiceOrderListJson.InvoiceOrderList data, int pos) {
        if (data == null) {
            return;
        }

        data.setChecked(!data.isChecked());

        mInvoiceListAdapter.setData(pos, data);

        boolean isCheckAll = true;

        String totalMoney = "0.0";

        int total = 0;

        InvoiceOrderListJson.InvoiceOrderList tempData;

        for (int i = 0; i < mInvoiceListAdapter.getData().size(); i++) {
            tempData = mInvoiceListAdapter.getItem(i);

            if (!tempData.isChecked()) {
                isCheckAll = false;
            } else {
                total++;
                totalMoney = ArithmeticUtil.addAmount(totalMoney, ArithmeticUtil.mulScaleAmount(tempData.getPay_amount(), tempData.getNum()));
            }
        }

        if (isCheckAll) {
            ll_invoice_list_bottom.setCheckedAll(true);
        } else {
            ll_invoice_list_bottom.setCheckedAll(false);
        }

        ll_invoice_list_bottom.setTotalText(String.valueOf(total), totalMoney);
    }

    //获取选择开票的订单
    private String getSelectOrderId() {
        if (CommonUtils.isEmptyList(mInvoiceListAdapter.getData())) {
            return "";
        }

        StringBuilder stringBuilder = new StringBuilder();

        List<String> mIds = new ArrayList<>();

        //遍历问题id集合和答案集合拼接字符串 作为单数请求服务器
        for (int i = 0; i < mInvoiceListAdapter.getData().size(); i++) {
            if (mInvoiceListAdapter.getItem(i).isChecked()) {
                mIds.add(mInvoiceListAdapter.getItem(i).getId());
            }
        }

        for (int i = 0; i < mIds.size(); i++) {
            stringBuilder.append(mIds.get(i));

            if (i < mIds.size() - 1) {
                stringBuilder.append(",");
            }
        }

        return stringBuilder.toString();
    }

    //获取待开发票的订单列表
    private void getInvoiceOrderList() {
        showLoadingDialog();

        InvoiceApiIO.getInstance().getInvoiceOrderList(new APIRequestCallback<InvoiceOrderListJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(InvoiceOrderListJson res) {
                if (mInvoiceListAdapter == null) {
                    return;
                }

                mInvoiceListAdapter.getData().clear();
                mInvoiceListAdapter.addData(res.getData());
                mInvoiceListAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mInvoiceListAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    public interface OnInvoiceListSureListener {
        void onInvoiceSureClick(String value);
    }
}
